/**
 * 
 */
package jvs.peer.xmpp;

import jvs.peer.io.MessageConstant;
import jvs.peer.io.MessageListener;
import jvs.peer.util.Log;

import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;

/**
 * @author qiangli
 * 
 */
public class XmppMessageListener implements PacketFilter, PacketListener {

	private MessageListener listener;
	private String peer;
	private String thread;

	public XmppMessageListener(String peer, String thread,
			MessageListener listener) {
		this.peer = peer;
		this.thread = thread;
		this.listener = listener;
	}

	public boolean accept(Packet packet) {
		if (XmppUtil.isLoopback(packet)) {
			return false;
		}
		if (!(packet instanceof Message)) {
			return false;
		}

		Message msg = (Message) packet;
		if (!msg.getType().equals(Message.Type.normal)) {
			return false;
		}

		String tid = msg.getThread();
		String from = msg.getFrom();
		if (tid == null || from == null) {
			return false;
		}

		Object obj = packet.getProperty(MessageConstant.UDP);
		if (Log.DEBUG) {
			Log.log(this, " accepting id: " + tid + " from: "
				+ from + " to: " + packet.getTo());
		}
		if (obj == null) {
			return false;
		}
		
		return (tid.equals(thread) && from.equals(peer));
	}

	public void processPacket(Packet packet) {
		Message msg = (Message) packet;
		listener.onMessage(msg.getBody());
	}

	public MessageListener getListener() {
		return listener;
	}

	public String getPeer() {
		return peer;
	}

	public String getThread() {
		return thread;
	}
}
